package com.tongguan.paypos.base;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;

import com.tongguan.paypos.R;
import com.tongguan.paypos.activity.LoginActivity;
import com.tongguan.paypos.common.AppConstants;
import com.tongguan.paypos.common.User;
import com.tongguan.paypos.utils.DateUtils;
import com.tongguan.paypos.utils.L;
import com.tongguan.paypos.common.RequestCallback;
import com.tongguan.paypos.utils.SPUtils;
import com.tongguan.paypos.view.CustomProgressDialog;

import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.Call;

/**
 * Created by Joylive on 2016/10/13 .
 * 所以Activity类必须继承此类
 */

public abstract class BaseActivity extends AppCompatActivity {
    private static final int TIMER_DELAYED = 10;
    protected Context context;
    protected Map<String, Object> params;
    protected Timer mTime;
    private InputMethodManager imm;
    protected CustomProgressDialog mDialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // AppManager.getInstance().addActivity(this); //备注 ： app设计是长留主界面 不需要退出 ，将android:launchMode="singleTask" 模式
        //设置竖屏显示
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        this.context = this;
        imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        mDialog = new CustomProgressDialog(this, "加载中...");
    }

    /**
     * Activity 跳转
     */
    protected void jumpAct(Class<? extends BaseActivity> activity) {
        jumpAct(activity, false);
    }

    protected void jumpAct(Class<? extends BaseActivity> activity, boolean isLogin) {
        jumpAct(activity, isLogin, false);
    }

    protected void jumpAct(Class<? extends BaseActivity> activity, boolean isLogin, boolean isFinish) {
        jumpAct(activity, null, isLogin, isFinish);
    }

    protected void jumpAct(Class<? extends BaseActivity> activity, Bundle bundle, boolean isLogin, boolean isFinish) {
        if (isLogin) {
            everydaySignIn();
            if (!isLogin()) {
                return;
            }
        }
        Intent intent = new Intent(this, activity);
        if (bundle != null) {
            intent.putExtras(bundle);
//            L.d("Bundle", "jumpAct: "+ bundle.toString());//打印bundle
        }
        startActivity(intent);
        if (isFinish) {
            finish();
        }
    }

    /**
     * Fragment之间的切换
     */
    protected void jumpFrm(Fragment from, Fragment to, int id, String tag) {
        if (to == null) {
            return;
        }
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        if (from == null) {
            transaction.add(id, to, tag);
        } else {
            transaction.hide(from);
            if (to.isAdded()) {
                transaction.show(to);
            } else {
                transaction.add(id, to, tag);
            }
        }
        transaction.commitAllowingStateLoss();
    }

    /**
     * 初始化标题栏
     */
    protected void initTile(int resid, boolean isBack) {
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        TextView textView = (TextView) findViewById(R.id.toolbar_title);
        textView.setText(resid);
        if (isBack) {
            toolbar.setNavigationIcon(R.drawable.ic_back_btn_white);
        }
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        if (isBack) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home: //屏蔽 toolbar 返回
                onBackPressed();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }


    /**
     * 登录状态
     *
     * @return
     */
    public boolean isLogin() {
        if (User.getInstance().isLoginStatus()) {
            L.d("已经登录");
            return true;
        } else {
            L.d("还未登录");
            jumpAct(LoginActivity.class);
            return false;
        }
    }

    /**
     * 每日签到
     */
    public void everydaySignIn() {
        String sp = (String) SPUtils.getSp(context, AppConstants.EVERYDAY_SIGN_IN, "");
        String date = DateUtils.getDate();
        if (!date.equals(sp)) {
            L.d("sp - data : " + sp + " - " + date);
            User.getInstance().setLoginStatus(false);
            SPUtils.setSP(context, AppConstants.EVERYDAY_SIGN_IN, date);
        }
    }

    //不返回onFail
    public abstract class AbstractRequestCallback implements RequestCallback.HttpCallback {
        public abstract void onResponse(String response, int id);

        public void onError(Call call, Exception e, int id) {

        }
    }


    protected void setTimer(Handler handler, int what) {
        setTimer(handler, what, TIMER_DELAYED);
    }

    protected void setTimer(Handler handler, int what, int time) {
        mTime = new Timer();
        mTime.schedule(new TimerTask() {
            int times = time * 1000;

            @Override
            public void run() {
                handler.sendMessage(handler.obtainMessage(what, times));
                times -= 1000;
            }
        }, 1000, 1000);
    }


    @Override
    public void onBackPressed() {
        View view = getCurrentFocus();
        // 如果没有获得焦点的 view，创建一个新的，从而得到一个窗口的 token
        if (view == null) {
            view = new View(this);
        }
        if (imm.isActive(view)) {
            //隐藏软盘
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
        super.onBackPressed();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_MENU) {//屏蔽menu键
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mTime != null) {
            mTime.cancel();
        }
        if (mDialog != null ) {
            mDialog.dismiss();
            mDialog=null;
        }
    }

}
